import React, { useEffect, useState } from 'react'
import { Button, ButtonProps, Form, Input, message, Modal, ModalProps, Space } from 'antd'
import { ServerResult, UserRole } from '../../../server/interface';
import { api_role } from '../../apis';
import { PermSelect } from '../perm/PermSelect';
import { updateRole } from '../../store';

export interface RoleModalProps {
    modalProps?: ModalProps;
    role?: UserRole;
    onOk?: () => void;
    buttonProps?: ButtonProps;
    children?: React.ReactNode;
}
export const RoleModal = (props: RoleModalProps) => {
    const { buttonProps = {}, modalProps = {}, role, onOk, children } = props;
    const [form] = Form.useForm();
    const [visible, setVisible] = useState(false);
    const isUpdate = !!role?.key;
    const readonly = !!role?.readonly;

    useEffect(function () {
        if (visible) {
            if (role) {
                form.setFieldsValue(role);
            } else {
                form.resetFields();
            }
        }
    }, [role, visible])

    const onFinish = () => {
        form.validateFields().then(async (values: UserRole) => {
            let res: ServerResult<any>
            if (isUpdate) {
                res = await api_role.update({ ...values, key: role?.key })
            } else {
                res = await api_role.create([{ ...values }])
            }
            if (res.success) {
                setVisible(false);
                message.success('保存成功');
                updateRole();
                onOk?.();
            }
        })
    }

    const title = isUpdate ? '修改' : '创建';
    return <>
        <Button {...buttonProps} onClick={() => setVisible(true)}>{children || title}</Button>
        <Modal {...modalProps}
            title={ title }
            open={visible}
            onCancel={() => setVisible(false)}
            footer={null}
        >
            <Form form={form} onFinish={onFinish} labelCol={{ span: 6 }} wrapperCol={{ span: 16 }} >
                <Form.Item name="name" label="角色名称" required rules={[{ required: true }]}>
                    <Input placeholder="请输入角色名称" />
                </Form.Item>
                {!readonly && <Form.Item name="permissions" label="权限" required rules={[{ required: true }]}>
                    <PermSelect mode="multiple" />
                </Form.Item>}
                <Form.Item name="desc" label="角色描述">
                    <Input placeholder='请输入角色描述' />
                </Form.Item>
                <Form.Item wrapperCol={{ offset: 6, span: 16 }}>
                    <Space>
                        <Button type="primary" htmlType="submit">{title}</Button>
                        <Button onClick={() => setVisible(false)}>取消</Button>
                    </Space>
                </Form.Item>
            </Form>
        </Modal>
    </>
}